import * as step from '@flow-step/step-toolkit'
import path from 'path'
import process from 'process'
import {setup} from "./step"
import fs from 'fs'

const FLOW_JOB_TOKEN: string = 'FLOW_JOB_TOKEN'
const NPM_PRIVATE_REPO_CONFIG_PATH: string = 'NPM_PRIVATE_REPO_CONFIG_PATH'
const ENV_USE_FOREIGN_CLUSTER: string = 'useForeignCluster'

async function runStep(): Promise<void> {
    const useForeignCluster: string | undefined = process.env[ENV_USE_FOREIGN_CLUSTER]
    if (useForeignCluster === 'true') {
        step.info("Please DO NOT use domestic repository or proxy when use oversea build cluser!")
        return
    }
    const flowJobToken: string | undefined = process.env[FLOW_JOB_TOKEN]
    if (flowJobToken == undefined) {
        let errMsg = 'missing FLOW_JOB_TOKEN'
        throw new Error(errMsg)
    }

    const npmPrivateRepoConfigPath: string | undefined = process.env[NPM_PRIVATE_REPO_CONFIG_PATH]
    if (npmPrivateRepoConfigPath == undefined) {
        let errMsg = 'missing NPM_PRIVATE_REPO_CONFIG_PATH'
        throw new Error(errMsg)
    }

    const absolutePath = path.resolve(npmPrivateRepoConfigPath)
    step.info(`absolute npmPrivateRepoConfigPath: ${absolutePath}`)
    await setup(flowJobToken, absolutePath)
}

runStep()
    .then(function () {
        step.success('run step successfully!')
    })
    .catch(function (err: Error) {
        step.error(err.message)
        process.exit(-1)
    })
